using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using System;

namespace XLib.Network.Http
{
    public class HttpRequest : BaseHttpRequest
    {
        public HttpRequest(string method, string url, Action<long, string, string> onHttpResponse)
        {
            this.method = method;
            this.url = url;
            this.onHttpResponse = onHttpResponse;
        }
        
        public override void Start()
        {
            www = new UnityWebRequest(url, method);
            www.downloadHandler = new DownloadHandlerBuffer();
            www.SendWebRequest();
        }

        public override void Stop()
        {
            www?.Abort();
            www = null;
            onHttpResponse = null;
        }

        public override bool Update()
        {
            if (www.isDone)
            {
                onHttpResponse?.Invoke(www.responseCode, www.downloadHandler.text, www.error);
                return false;
            }
            return true;
        }
    }

    public class HttpManager : HttpRequestManager
    {
        public static BaseHttpRequest Get(string url, Action<long, string, string> onHttpResponse)
        {
            var httpRequest = new HttpRequest(UnityWebRequest.kHttpVerbGET, url, onHttpResponse);
            HttpManager.Instance.AddRequest(httpRequest);
            return httpRequest;
        }
    }
}